package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.VerifyCodeUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    UserInfoMapper userInfoMapper;

    @Override
    public void getCode(String phone) {
//        判断手机号码是否为空
        if (!StringUtils.hasText(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        // 判断是否在60s内发送过短信
        String codeKey = RedisConstant.APP_LOGIN_PREFIX + phone;
//        hasKey方法判断是否存在key
        Boolean restle = redisTemplate.hasKey(codeKey);
        if (restle) {
//          设置过期时间
            Integer appLoginCodeTtlSec = RedisConstant.APP_LOGIN_CODE_TTL_SEC;
//          查询在数据库中codeKey验证码的过期时间
//            getExpire方法获取key的过期时间
            Long expire = redisTemplate.getExpire(codeKey);
//            判断剩余时间
            long liveTime = appLoginCodeTtlSec - expire;
//            如果剩余时间小于60秒，则抛出异常
            if (liveTime < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }


//        调用genrateCode方法生成随机6位验证码
        String code = VerifyCodeUtil.genrateCode(6);
//        sendMsg方法发送短信验证码
        smsService.sendMsg(phone, code);
//        将验证码存入redis中
        redisTemplate.opsForValue().set(codeKey, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
//        判断手机号码是否为空
        if (!StringUtils.hasText(loginVo.getPhone())) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
//        判断验证码是否为空
        if (!StringUtils.hasText(loginVo.getCode())) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
//        校验验证码是否 存在/正确
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
//        opsForValue().get(key)是获取key对应的value
        Object code = redisTemplate.opsForValue().get(key);
        if (code == null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
//        校验验证码是否 正确
        if (!code.equals(loginVo.getCode())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
//        判断是否存在 不存在则添加
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, loginVo.getPhone()));
        if (userInfo == null) {
//            创建用户对象
            userInfo = new UserInfo();
//            添加用户信息
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setNickname("用户" + loginVo.getPhone().substring(6));
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfoMapper.insert(userInfo);
        }
//        判断用户状态是否正常
        if (userInfo.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
//        生成token
        String token = JwtUtil.createToken(userInfo.getId(), loginVo.getPhone());
        return token;
    }


}
